<!--
 * @author  dumeng
 新建水印
-->
<template>
  <div class="courseware-create">
    <el-dialog
      v-el-drag-dialog
      :lock-scroll="false"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :visible.sync="visible"
      :title="info.subjectName ? '编辑水印' : '新建水印'"
      center
      width="600px"
      custom-class="courseware-create-dialog"
      @close="$emit('close')"
    >
      <section v-loading="loading" class="courseware-create-main">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="form">
          <el-form-item label="模板名称" prop="watermarkName">
            <el-input v-model.trim="form.watermarkName" maxlength="100" placeholder="" />
          </el-form-item>
          <el-form-item label="模板图标" prop="watermarkIcon">
            <img
              v-if="form.watermarkIcon"
              class="upload-img"
              :src="uploadFile.view + form.watermarkIcon"
              @click="handleFileUpload('image')"
            >
            <div v-else class="icon-wrap" @click="handleFileUpload('image')">
              <i class="el-icon-plus avatar-uploader-icon" />
            </div>
          </el-form-item>
          <el-form-item label="位置" prop="watermarkSide">
            <!-- <el-input v-model.trim="form.watermarkSide" maxlength="100" placeholder="" /> -->
            <el-select v-model="form.watermarkSide" placeholder="请选择位置">
              <el-option
                v-for="item in dict['SYWZ']"
                :key="item.dictValue"
                :label="item.dictName"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="方向" prop="direction">
            <el-input v-model.trim="form.direction" maxlength="100" placeholder="" />
          </el-form-item> -->

          <el-form-item label="横向间隔" prop="horizontalSpacing">
            <el-input v-model.trim="form.horizontalSpacing" maxlength="100" placeholder="" />
          </el-form-item>

          <el-form-item label="纵向间隔" prop="longitudinalSpacing">
            <el-input v-model.trim="form.longitudinalSpacing" maxlength="100" placeholder="" />
          </el-form-item>
          <!-- <el-form-item label="使用场景" prop="watermarkType">
            <el-select v-model="form.watermarkType" placeholder="请选择使用场景">
              <el-option v-for="item in dict['SYCJ']" :key="item.dictValue" :label="item.dictName" :value="item.dictValue" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="是否启用" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio label="ZT01">启用</el-radio>
              <el-radio label="ZT02">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input v-model.trim="form.sort" maxlength="100" placeholder="" />
          </el-form-item>
        </el-form>
      </section>
      <section class="courseware-create-footer">
        <el-button style="padding: 10px 30px;" @click="$emit('close')">取 消</el-button>
        <el-button type="primary" @click="onSubmint('form')">确 定</el-button>
      </section>
    </el-dialog>
    <image-no-cropper-upload
      v-if="uploadFile.showUpload === 1"
      ref="imageUpload"
      :accept="uploadFile.accept"
      :limit="1"
      :show-chunks="true"
      :multiple="false"
      :chunk-size="uploadFile.chunksize"
      @close="uploadFile.showUpload = -1"
      @success="uploadSuccess"
    >
      <div slot="tip" class="upload-tip">
        <i class="el-icon-info" />
        :
        {{ uploadFile.fileType | filterTip }}
      </div>
    </image-no-cropper-upload>
  </div>
</template>

<script>
import ImageNoCropperUpload from '@/components/ImageNoCropperUpload'
import {getDictByCode, insert, update} from '../api/createCourseware'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
  name: 'Create',
  components: {ImageNoCropperUpload},
  directives: {elDragDialog},
  filters: {
    filterTip(ft) {
      if (ft === 'image') {
        return '只能上传：图片文件'
      } else if (ft === 'video') {
        return '只能上传：视频文件'
      } else {
        return '请上传附件'
      }
    }
  },
  props: {
    info: {
      type: Object,
      default: () => {
      }
    }
  },
  data() {
    return {
      loading: false,
      dict: [],
      form: {
        id: '',
        watermarkName: '', // 模板名称
        watermarkIcon: '', // 模板图标
        watermarkSide: '', // 位置
        // direction: '', // 方向
        horizontalSpacing: '10', // 横向间隔
        longitudinalSpacing: '10', // 纵向间隔
        // watermarkType: '', // 使用场景
        status: 'ZT01', // 状态
        sort: 0 // 排序
      },
      rules: {
        watermarkName: [{required: true, message: '请输入模板名称', trigger: 'change'}],
        watermarkIcon: [{required: true, message: '请上传模板图标', trigger: 'change'}]
        // watermarkSide: [{ required: true, message: '请输入位置', trigger: 'change' }],
        // direction: [{ required: true, message: '请输入方向', trigger: 'change' }],
        // horizontalSpacing: [{ required: true, message: '请输入横向间隔', trigger: 'change' }],
        // longitudinalSpacing: [{ required: true, message: '请输入纵向间隔', trigger: 'change' }],
        // watermarkType: [{ required: true, message: '请选择使用场景', trigger: 'change' }]
      },
      state: '',
      visible: true,
      selectSubjectImg: '', // 选择的视频截图
      subjectImgType: 1, // 封面选择方式  1：从视频截图中取   2：自定义上传
      showImageUpload4base64: false, // 显示base64图片上传裁剪
      uploadFile: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0,
        showUpload: -1, // 1视频 2图片 3附件
        accept: '',
        fileType: '',
        fileIndex: 0
      },
      isOss: sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG') || false
    }
  },
  created() {
    this.state = this.$route.query.type === 'u' ? 'update' : 'create'
    this.getDict('SYCJ')
    this.getDict('SYWZ')
  },
  methods: {
    handleFileUpload(fileType, i) {
      if (fileType === 'image') {
        this.uploadFile.fileType = fileType
        this.uploadFile.accept = 'image/*'
        this.uploadFile.showUpload = 1
      }
    },
    uploadSuccess(id, files) {
      if (id) {
        const fileType = this.uploadFile.fileType
        if (fileType === 'image') {
          this.form.watermarkIcon = id
        }
      }
      this.uploadFile.showUpload = -1
    },
    onSubmint() {
      if (this.info.id) {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form)
            return new Promise((resolve, reject) => {
              update(params)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '更新成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$emit('close')
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            console.log('error update!!')
            return false
          }
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form)
            return new Promise((resolve, reject) => {
              insert(params)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$emit('close')
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    },
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code)
          .then((res) => {
            const datas = res.data.data && res.data.data.length > 0 ? res.data.data[0].list : []
            this.$set(this.dict, code, datas)
            this.$forceUpdate()
          })
          .catch((error) => {
            reject(error)
          })
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.courseware-create {
  .courseware-create-dialog .el-dialog__body {
    min-height: 750px;
    overflow-y: auto;
  }

  .select-data {
    display: inline-block;
    background: rgba(246, 246, 246, 1);
    border-radius: 4px;
    font-size: 14px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    color: rgba(51, 51, 51, 1);
    padding: 0 10px;
    margin-right: 5px;
    margin-bottom: 8px;

    i {
      cursor: pointer;
      padding-left: 5px;
    }
  }

  .selectbtn {
    display: inline-block;
    width: 120px;
    background: rgba(255, 255, 255, 1);
    @include border-color(1px, dotted, $mainColor);
    border-radius: 4px;
    font-size: 14px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    @include font-color($mainColor);
    text-align: center;
    cursor: pointer;
  }

  .courseware-create-footer {
    /* position: absolute;
    left: 0;
    right: 0;
    bottom: 0; */
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }

  .courseware-preview {
    .el-dialog__body {
      position: relative;

      .full {
        position: absolute;
        width: 100px;
        height: 58px;
        right: 50px;
        top: -58px;
        display: flex;
        align-items: center;
        text-align: right;
      }
    }
  }

  .icon-wrap {
    width: 300px;
    height: 160px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(247, 247, 248, 1);
    border: 1px solid rgba(226, 227, 232, 1);
    border-radius: 4px;

    .avatar-uploader-icon {
      font-size: 48px;
      color: #dadada;
      width: 300px;
      text-align: center;
    }
  }

  .upload-img {
    display: block;
    width: 300px;
    height: 160px;
    border-radius: 4px;
  }
}
</style>
